from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from userapp.user_form import UserForm
from userapp.login_form import LoginForm
from django.contrib.auth.models import User
from django.contrib import auth
from timelineapp.models import Timeline, TimelineCategory
from eventapp.models import Event
from permissionapp.views import check_invitations 

def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST['email']
            password = request.POST['password']
            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:
                # Correct password, and the user is marked "active"
                auth.login(request, user)
                user_id = '%s' % user.id
                
                # Redirect to previous page
                if not "previous" in request.POST:
                    return HttpResponseRedirect('/user')
                else:
                    return HttpResponseRedirect(request.POST["previous"])
            else:
                # Show an error page
                return render_to_response('login.html', 
                                          {'error_message':'E-mail ou senha fornecidos incorretos.'})
    else:
        previous = ""
        if ("previous" in request.GET):
            previous = request.GET["previous"]
            
        if not request.user.is_authenticated():
            form = UserForm()
            return render_to_response('login.html', {'form':form, 'previous':previous})
        else:
            return HttpResponseRedirect('/user')

def logout(request):
    auth.logout(request)
    return HttpResponseRedirect('/')
    
def create_user(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            name_data = form.cleaned_data['first_name']
            email_data = form.cleaned_data['email']
            password_data = form.cleaned_data['password']
            
            new_user = User(username=email_data, first_name=name_data, email=email_data)
            new_user.set_password(password_data)
            new_user.save()
            
            check_invitations(new_user)
            #send_mail('Bem-vindo ao Crowd Timeline', 'Seja bem-vindo ao maior servico de criacao de timelines colaborativas da Internet!', 
            #'crowdtimeline@gmail.com',[email_data], fail_silently=False)
            
            login(request)
            return HttpResponseRedirect('/user')
    else:
        form = UserForm()
           
    return render_to_response('user_form.html', {'form':form})

def show_user(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login')
    try:
        user = User.objects.get(pk=request.user.id)
        user_title = 'Usuario %s' % user.id
        username = '%s' % user.email
        user_name = '%s' % user.first_name
        user_email = '%s' % user.email
    except User.DoesNotExist:
        user_title = 'Usuario Inexistente.'    
    return render_to_response('user.html', locals())

def edit_user(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login')
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            name_data = form.cleaned_data['first_name']
            email_data = form.cleaned_data['email']
            password_data = form.cleaned_data['password']
            
            updated_user = User(id=request.user.id, username=email_data, 
                                first_name=name_data, email=email_data)
            updated_user.set_password(password_data)
            updated_user.save()
            username = '%s' % updated_user.username
            return HttpResponseRedirect('/user')
        #else:
            #print form.errors
    else:
        form = UserForm()
        try:
            user = User.objects.get(id=request.user.id)
            user_name = user.first_name
            user_email = user.email
            user_title = "Edit Usuario %s" % request.user.id
        except User.DoesNotExist:
            user_title = 'Usuario Inexistente.'
            return render_to_response('user_edit_form.html', {'form':form})
        return render_to_response('user_edit_form.html', {'form':form})

def delete_user(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login')
    
    user = User.objects.get(id=request.user.id)
    user.is_active = False
    user.save()
    return logout(request)

def list_user_events(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login')
    
    action = "list"
    category =  TimelineCategory.objects.order_by('name')
    selected_category = 0
    
    if request.method == 'GET':
        if ("timeline_category" in request.GET):
            selected_category = int(request.GET["timeline_category"]) 
        
    if not selected_category:
        events = Event.objects.filter(creator=request.user.id)
        ev_timelines = []
        for e in events:
            ev = Event.objects.get(id=e.id)
            timelines = Timeline.objects.filter(events=ev)
            for t in timelines:
                ev_timelines.append(t)
        events_timelines = []
        for i in range(len(ev_timelines)):
            repeated = False
            for j in range(i+1,len(ev_timelines)):
                if ev_timelines[i]==ev_timelines[j]:
                    repeated=True
            if not repeated:
                events_timelines.append(ev_timelines[i])
            repeated=False
        
        groups = []
        
        for t in events_timelines:
            d = {}                   
            d["timeline"] = t
            d["events"] = []
            events_list = Event.objects.filter(timeline=t)
            for e in events_list:
                d["events"].append(e)
            groups.append(d)
            
    else:
        events = Event.objects.filter(creator=request.user.id)
        ev_timelines = []
        for e in events:
            ev = Event.objects.get(id=e.id)
            timelines = Timeline.objects.filter(events=ev, categories=selected_category)
            for t in timelines:
                ev_timelines.append(t)
        events_timelines = []
        for i in range(len(ev_timelines)):
            repeated = False
            for j in range(i+1,len(ev_timelines)):
                if ev_timelines[i]==ev_timelines[j]:
                    repeated=True
            if not repeated:
                events_timelines.append(ev_timelines[i])
            repeated=False
        
        groups = []
        
        for t in events_timelines:
            d = {}                   
            d["timeline"] = t
            d["events"] = []
            events_list = Event.objects.filter(timeline=t)
            for e in events_list:
                d["events"].append(e)
            groups.append(d)
        
    return render_to_response('user_events.html', locals())

def list_user_timelines(request):
    
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login')
    
    action = "list"
    category =  TimelineCategory.objects.order_by('name')
    selected_category = 0
    
    if request.method == 'GET':
        if ("timeline_category" in request.GET):
            selected_category = int(request.GET["timeline_category"]) 
        
    if not selected_category:
        timelines = Timeline.objects.filter(creator=request.user.id)
    else:
        timelines = Timeline.objects.filter(creator=request.user.id, categories=selected_category)
        
    return render_to_response('user_timelines.html', locals())